#include "yk_form_wzkccx.h"
#include "ui_yk_form_wzkccx.h"
#include <QSettings>
#include <QMessageBox>
#include <QJsonDocument>
#include <QHeaderView>
#include <QSqlError>
#include <QSqlRecord>
#include "pub_var.h"
#include <QJsonObject>
#include <QJsonArray>
#include <windows.h>
#include <QLibrary>
#include <QAxObject>

Form_wzkccx::Form_wzkccx(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Form_wzkccx)
{
    ui->setupUi(this);

    //恢复当前窗口位置
    QSettings setIni("clin.ini", QSettings::IniFormat);
    QRect rct = setIni.value("windowState/wzkccx").toRect();
    this->setGeometry(rct);

    //数据库连接
    qrm = new QSqlQuery(pub::db_m);
    qrmt = new QSqlQuery(pub::db_m);
    qro = new QSqlQuery(pub::db_o);
    mdList1 = new QSqlQueryModel();
    mdList2 = new QSqlQueryModel();
    mdList3 = new QSqlQueryModel();
    mdList4 = new QSqlQueryModel();
    mdSearchPop = new QSqlQueryModel();


    //提取当前 操作人员有权限的科室
//    sq = " select role_dept "
//         " from com_privileges "
//         " WHERE type = 'dept' and code = '" + pub::usr_code + "'";
//    qDebug()<<"提取操作员有权限的库存单位："<<sq;
//    qrmt->exec(sq);

//    ui->cbbStoreDept->clear();

//    while(qrmt->next())
//    {
//        QString tmp = qrmt->value(0).toString();

//        if(store_depts.indexOf(tmp) > -1)
//        {
//            ui->cbbStoreDept->addItem(tmp);
//        }
//    }

    ui->cbbRelate->addItem("全部");   //默认往来关系，全部

    sq  = "select dept_name, dept_code, dept_type from com_department "
          " where dept_type in ('L') order by dept_type,dept_name";
    store_depts = pub::fillCombo(ui->cbbStoreDept, sq, -1);
    ui->cbbStoreDept->addItem("全部");
    //ui->cbbStoreDept->setCurrentIndex( ui->cbbStoreDept->count() - 1 );
    ui->cbbStoreDept->setCurrentIndex(0);

    dlgDelay = new Pub_pop_delay();
    dlgGetItem = new Pub_pop_get_item();

    //ui->deBegin_3->setDate(QDate::currentDate());
    //ui->deEnd_3->setDate(QDate::currentDate());
    ui->deBegin->setDate(QDate::currentDate());
    ui->deEnd->setDate(QDate::currentDate());

    ui->tabWidget->setCurrentIndex(0);  //库存查询页面
    //    sqlThread = new sqThread();
    //    connect( sqlThread, &sqThread::message, this, &Form_ys_bzgl::threadMsg);

    //项目成本临时表
    sq = "create temporary table if not exists tmp_drug_cost (";
    sq += "atinc int auto_increment not null key, ";  //流水编码
    sq += "日期 VARCHAR(12) not null , ";  //
    sq += "西药 VARCHAR(12) not null,";          //
    sq += "中成药 VARCHAR(12) not null, ";      //
    sq += "中草药 VARCHAR(12) not null, ";      //
    sq += "小计 VARCHAR(12) not null";               //
    sq += ") ";   //
    if(!qrm->exec(sq))
    {
        QMessageBox::information(this,"note",qrm->lastError().text());
        return;
    }

    //自制项目临时表
    sq = "create temporary table if not exists tmp_self_drug (";
    sq += "atinc int auto_increment not null key, ";  //流水编码
    sq += "用药诊室 VARCHAR(12) not null , ";  //
    sq += "项目类别 VARCHAR(12) not null,";          //
    sq += "物资项目名称 VARCHAR(12) not null, ";      //
    sq += "规格 VARCHAR(12) not null, ";      //
    sq += "单位 VARCHAR(12) not null , ";  //
    sq += "数量 VARCHAR(12) not null,";          //
    sq += "进价 VARCHAR(12) not null, ";      //
    sq += "零售价 VARCHAR(12) not null,";               //
    sq += "进价总额 VARCHAR(12) not null, ";      //
    sq += "零售总额 VARCHAR(12) not null,";               //
    sq += "差价 VARCHAR(12) not null";               //
    sq += ") ";   //
    if(!qrm->exec(sq))
    {
        QMessageBox::information(this,"note",qrm->lastError().text());
        return;
    }

}

Form_wzkccx::~Form_wzkccx()
{
    delete ui;
}

void Form_wzkccx::closeEvent(QCloseEvent *event)
{
    Q_UNUSED(event);
    QSettings setIni("clin.ini", QSettings::IniFormat);
    setIni.setValue("windowState/wzkccx", QVariant(this->geometry()));

    emit destroyW( "yk_wzkccx" );

}

void Form_wzkccx::on_pbExit_clicked()
{
    close();
}

void Form_wzkccx::on_pbFresh_clicked()
{
    //storage_code,
    QString dept_code = "";
    if(ui->cbbStoreDept->currentText() != "全部")
    {
        dept_code = pub::getStr(store_depts, "^", pub::searchStr(store_depts, "^", ui->cbbStoreDept->currentText()) + 1);
    }
    QString sq;

    QString condition_num = ""; //筛选条件，库存数量

    if(ui->ckbNo0->isChecked())
    {
        condition_num = " and sto.store_num > 0 ";
    }

    QString condition_dept = ""; //筛选条件，库存单位

    if(!dept_code.isEmpty())
    {
        condition_dept = " and sto.storage_code = '" +  dept_code + "'";
    }

    QString condition_item = ""; //筛选条件，按单品种或者全部查询

    if(ui->ckbItem->isChecked())    //查询单个品种
    {
        if(ui->leName->text().isEmpty())
        {
            QMessageBox::information(this, "注意", "设置品种限定，但未指定品种信息！");
            return;
        }

        if(ui->rbItem->isChecked()) //按品规
        {
            condition_item = " and sto.item_name = '" +  ui->leName->text() + "'";
            condition_item += " and sto.specs = '" +  ui->leSpecs->text() + "'";
        }
        else if(ui->rbFactory->isChecked()) //按厂家
        {
            condition_item = " and sto.item_code = '" +  item_code + "'";
        }
        else if(ui->rb_batch_times->isChecked()) //按批次
        {
            condition_item = " and sto.item_code = '" + item_code + "'";
            if(!stock_no.isEmpty())
            {
                condition_item = " and sto.stock_no = '" + stock_no + "'";
            }
            //
        }
        else  //批号
        {
            condition_item = " and sto.item_code = '" +  item_code + "'";
            condition_item += " and sto.batch_no like '%" + ui->leBatch->text() + "%'";
        }
    }


    QString base_sql, order_field;

    order_field = " order by 库房名称, 物资项目名称 ";

    if(ui->rbItem->isChecked()) //按品规划分品种
    {
        base_sql = " (select max(sto.item_code) code ,"
                   " (select dept_name from COM_DEPARTMENT "
                   "     where DEPT_CODE = STO.storage_code and ROWNUM = 1) 库房名称,"
                   " sto.item_name 物资项目名称, "
                   " sto.specs 规格, sto.pack_unit 包装单位, "
                   " sum(store_num / pack_qty) 包装数量, storage_code"
                   " FROM mat_com_stockdetail sto "
                   " WHERE 1 = 1 ";
        base_sql += condition_num + condition_dept + condition_item;
        base_sql += " group by STO.storage_code, sto.item_name , "
                    " sto.specs , sto.pack_unit )";

        sq = " select 库房名称, 物资项目名称, 规格, 包装单位, 包装数量 from ";
        sq += base_sql + order_field;

    }

    else if(ui->rbFactory->isChecked())    // 按厂家划分
    {
        base_sql = "(select (SELECT dept_name FROM COM_DEPARTMENT "
                   "      WHERE DEPT_CODE = STO.storage_code AND ROWNUM = 1 ) 库房名称,"
                   " (SELECT company_name FROM mat_com_company com  "
                   "     WHERE com.company_code = sto.factory_code AND ROWNUM = 1 ) 生产厂家,"
                   " sto.item_name 物资项目名称,sto.specs 规格, "
                   " max(STO.factory_code) FACTORY_CODE, sto.pack_unit 包装单位,"
                   " SUM (store_num / pack_qty) 包装数量, "
                   " sto.item_code 项目编码, STO.storage_code "
                   " FROM MAT_COM_STOCKDETAIL sto WHERE 1 = 1";
        base_sql += condition_num + condition_dept + condition_item;
        base_sql += " group by STO.storage_code, sto.item_name, "
                    " sto.specs, sto.pack_unit,  sto.item_code,sto.factory_code)";

        sq = " select 库房名称, 物资项目名称, 规格, 包装单位, 包装数量, 生产厂家 from ";
        sq += base_sql + order_field;

    }
    else if(ui->rb_batch_times->isChecked())    // 按批次划分
    {
        base_sql = "(select (SELECT dept_name FROM COM_DEPARTMENT "
                   "     WHERE DEPT_CODE = STO.storage_code AND ROWNUM = 1 ) 库房名称,"
                   " (SELECT company_name FROM mat_com_company com  "
                   "     WHERE com.company_code = sto.factory_code AND ROWNUM = 1 ) 生产厂家,"
                   " sto.item_name 物资项目名称,sto.specs 规格, "
                   " max(STO.factory_code) FACTORY_CODE, sto.pack_unit 包装单位,"
                   " SUM (store_num / pack_qty) 包装数量, "
                   " sto.item_code 项目编码, STO.storage_code, sto.batch_no 批号 , sto.stock_no 批次"
                   " FROM MAT_COM_STOCKDETAIL sto WHERE 1 = 1";
        base_sql += condition_num + condition_dept + condition_item;
        base_sql += " group by STO.storage_code, sto.item_name, sto.specs, "
                    " sto.pack_unit, sto.item_code,sto.factory_code,sto.batch_no,sto.stock_no)";

        sq = " select 库房名称, 物资项目名称, 规格, 包装单位, 包装数量, 生产厂家，批号, 批次 from ";
        sq += base_sql + order_field;

    }
    else  //按批号划分
    {
        base_sql = "(select (SELECT dept_name FROM COM_DEPARTMENT "
                   "     WHERE DEPT_CODE = STO.storage_code AND ROWNUM = 1 ) 库房名称,"
                   " (SELECT company_name FROM mat_com_company com  "
                   "     WHERE com.company_code = sto.factory_code AND ROWNUM = 1 ) 生产厂家,"
                   " sto.item_name 物资项目名称,sto.specs 规格, "
                   " max(STO.factory_code) FACTORY_CODE, sto.pack_unit 包装单位,"
                   " SUM (store_num / pack_qty) 包装数量, "
                   " sto.item_code 项目编码, STO.storage_code, sto.batch_no 批号"
                   " FROM MAT_COM_STOCKDETAIL sto WHERE 1 = 1";
        base_sql += condition_num + condition_dept + condition_item;
        base_sql += " group by STO.storage_code, sto.item_name, sto.specs, "
                    " sto.pack_unit, sto.item_code,sto.factory_code,sto.batch_no)";

        sq = " select 库房名称, 物资项目名称, 规格, 包装单位, 包装数量, 生产厂家，批号 from ";
        sq += base_sql + order_field;

    }

    qDebug()<<"提取库存清单："<<sq;

    last_query_sql = sq;

    mdList1->setQuery(sq, pub::db_o);

    ui->tvList->setModel(mdList1);
    //int width = ui->tvList->horizontalHeader()->width();
    //pub::setColumnWidth(ui->tvList, "0.1^0.2^0.1^0.05^0.1^0.1^0.15^0^0^0.15^0.1^0", width);

}

void Form_wzkccx::on_pbSearch_clicked()
{
    QStringList searchResult;
    searchResult = getSearch(ui->cbbMode->currentText(), ui->leKey->text().trimmed());

    if(searchResult.size() == 0)
    {
        return;
    }
    else
    {
        ui->leName->setText(searchResult[0]);
        ui->leSpecs->setText(searchResult[1]);
        ui->leFactory->setText(searchResult[2]);
        ui->leBatch->setText(searchResult[3]);
        item_code = searchResult[4];
        factory_code = searchResult[5];
        stock_no = searchResult[6];
        stock_code = searchResult[7];

        ui->leHisCode->setText(item_code);
        qro->exec("select med_list_codg from fin_com_compare where fixmedins_hilist_id = '" + item_code + "'");
        qro->next();
        ui->leInsuCode->setText(qro->value(0).toString());

    }

    //设置间品种查询状态
    ui->ckbItem->setChecked(true);
}

QStringList Form_wzkccx::getSearch(QString mode, QString key_word)
{
    QStringList ret;
    sq = "SELECT distinct BASE.item_name 物资项目名称, BASE.specs 规格,";
    if(mode == "厂家")
    {
        sq += " (SELECT company_name FROM mat_com_company "
              "    WHERE company_code = base.FACTORY_CODE AND ROWNUM = 1 ) 生产厂家,";
        sq += "base.FACTORY_CODE, base.item_code, '', '' ";
        sq += " from mat_com_baseinfo base where valid_flag = '1' "
              " and ( spell_code like '%" + key_word.toUpper();
        sq += "%' or item_name like '%" + key_word + "%')";
    }
    else if(mode == "批号")
    {
        sq += " (SELECT company_name FROM mat_com_company"
              "     WHERE company_code = base.FACTORY_CODE AND ROWNUM = 1 ) 生产厂家,";
        sq += "base.FACTORY_CODE, base.item_code, ";
        sq += " STO.BATCH_NO 批号,''";  //, STO.GROUP_CODE
        sq += " FROM mat_com_baseinfo base, mat_com_stockdetail sto ";
        sq += " WHERE BASE.item_code = STO.item_code ";
        sq += " and BASE.valid_flag = '1'";
        sq += " and ( BASE.spell_code like '%" + key_word.toUpper();
        sq += "%' or BASE.item_name like '%" + key_word + "%')";

        if((ui->ckbNo0->isChecked() && ui->tabWidget->currentIndex() == 0)
                ||(ui->ckb_none_0_2->isChecked() && ui->tabWidget->currentIndex() == 1))
        {
            sq += " and sto.store_num > 0 and sto.storage_code = '" + current_dept_code + "' ";
        }
    }
    else if(mode == "批次")
    {
        sq += " (SELECT company_name FROM mat_com_company"
              "     WHERE company_code = base.FACTORY_CODE AND ROWNUM = 1 ) 生产厂家,";
        sq += "base.FACTORY_CODE, base.item_code, ";
        sq += " STO.BATCH_NO 批号, STO.stock_no 批次, sto.stock_code";  //
        sq += " FROM mat_com_baseinfo base, mat_com_stockdetail sto ";
        sq += " WHERE BASE.item_code = STO.item_code ";
        sq += " and BASE.valid_flag = '1'";
        sq += " and ( BASE.spell_code like '%" + key_word.toUpper();
        sq += "%' or BASE.item_name like '%" + key_word + "%')";

        if((ui->ckbNo0->isChecked() && ui->tabWidget->currentIndex() == 0)
                ||(ui->ckb_none_0_2->isChecked() && ui->tabWidget->currentIndex() == 1))
        {
            sq += " and sto.store_num > 0 and sto.storage_code = '" + current_dept_code + "' ";
        }
    }
    else if(mode == "品规")
    {
        sq += " '' 生产厂家, '' FACTORY_CODE, '' item_code, '' 批号, '' 批次";
        sq += " FROM mat_com_baseinfo base ";
        sq += " WHERE BASE.valid_flag = '1'";
        sq += " and ( BASE.spell_code like '%" + key_word.toUpper();
        sq += "%' or BASE.item_name like '%" + key_word + "%')";
    }
    else
    {
        QMessageBox::information(this, "注意", "检索模式无效！");
        return ret;
    }

    sq += " order by base.item_name, base.specs, FACTORY_CODE";

    if(mode == "批号")
    {
        sq += ", batch_no";
    }

    if(mode == "批次")
    {
        sq += ", stock_no";
    }

    qDebug()<<" select drug item : "<<sq;

    mdSearchPop->setQuery( sq , pub::db_o);

    if(mdSearchPop->rowCount() == 0)
    {
        QMessageBox::information(this, "注意", "指定关键字找不到有效的项目！");
        return ret;
    }
    else if(mdSearchPop->rowCount() == 1)
    {
        ret << mdSearchPop->record(0).value(0).toString();
        ret << mdSearchPop->record(0).value(1).toString();
        ret << mdSearchPop->record(0).value(2).toString();
        ret << mdSearchPop->record(0).value(5).toString();
        ret << mdSearchPop->record(0).value(4).toString();
        ret << mdSearchPop->record(0).value(3).toString();
        ret << mdSearchPop->record(0).value(6).toString();
        ret << mdSearchPop->record(0).value(7).toString();

        return ret;
    }
    else
    {
        if(mode == "厂家")
        {
            dlgGetItem->setDisplay(*mdSearchPop,QRect(200, 200, 800, 500),"","0.3^0.2^0.3^0^0^0^0^0^0");
        }
        else if(mode == "批号" )
        {
            dlgGetItem->setDisplay(*mdSearchPop,QRect(200, 200, 800, 500),"","0.25^0.2^0.25^0^0^0.2^0^0^0");
        }
        else if( mode == "批次")
        {
            dlgGetItem->setDisplay(*mdSearchPop,QRect(200, 200, 850, 500),"","0.2^0.15^0.2^0^0^0.15^0.15^0^0");
        }
        else
        {
            dlgGetItem->setDisplay(*mdSearchPop,QRect(200, 200, 800, 500),"","0.3^0.2^0^0^0^0^0^0^0");
        }

        dlgGetItem->setModal(true);
        dlgGetItem->exec();

        QString popRetStr = dlgGetItem->retStr();
        if(popRetStr.isEmpty())
        {
            return ret;
        }
        qDebug()<<"pop select return value is : "<<popRetStr;

        ret << pub::getStr(popRetStr, "^", 1);
        ret << pub::getStr(popRetStr, "^", 2);
        ret << pub::getStr(popRetStr, "^", 3);
        ret << pub::getStr(popRetStr, "^", 6);
        ret << pub::getStr(popRetStr, "^", 5);
        ret << pub::getStr(popRetStr, "^", 4);
        ret << pub::getStr(popRetStr, "^", 7);
        ret << pub::getStr(popRetStr, "^", 8);

        return ret;

    }
}

void Form_wzkccx::on_leKey_returnPressed()
{
    on_pbSearch_clicked();
}

void Form_wzkccx::on_pbFresh_2_clicked()
{
    if(!checkStatus(2))
    {
        return;
    }

    int pos;
    //库存类型, CLASS3_MEANING_CODE
    pos = pub::searchStr(store_depts, "^", ui->cbbStoreDept->currentText());
    QString store_type = pub::getStr(store_depts, "^", pos + 2);

    QString tmp_sq_fld_in, tmp_sq_fld_out, tmp_sq_tab_out;
    if(store_type == "P")
    {
        //药房
        tmp_sq_fld_in = " '' 患者姓名, '', '' 病志号, '' 医生, ";
        tmp_sq_fld_out = " reci.patient_name, reci.doct_code, reci.card_no, empl.empl_name, ";
        tmp_sq_tab_out = " LEFT JOIN mat_STO_RECIPE reci on reci.recipe_no = outp.recipe_no "
                         " LEFT JOIN COM_EMPLOYEE empl on empl.empl_code = reci.doct_code ";
    }


    sq = " select to_char(in_date ,'yyyy-mm-dd') 日期, "
         " com_priv_class3.class3_name 入出类型,"
         " in_num / pack_qty 变更数量, "
         " (priv_store_num + in_num ) /pack_qty 结存数量, "
         " pack_unit 单位,in_price 价格,"
         " in_price * in_num/pack_qty  金额 , "
         " batch_no 批号, TO_CHAR(valid_date,'yyyy-mm-dd') 效期, "
         " f_c.company_name 供货商, (case when in_state = '2' then '核准' else '待确认' end) 状态 , "
         " %1 "
         " in_date ord_date, item_name, specs "
         " from mat_com_input mat_in "
         " left JOIN mat_COM_COMPANY f_c on "
         "     f_c.company_CODE = mat_in.company_CODE "
         " left JOIN com_priv_class3 on "
         "     com_priv_class3.class3_code = in_class3 "
         "     and com_priv_class3.class2_code = '0510' "
         " where rownum < 10000 "
         " and mat_in.storage_code = '" + current_dept_code + "' ";

    if(!ui->ckbIn_2->isChecked())
    {
        //不查看入库记录, 设置入库常非条件
        sq += " and 1 > 2 ";
    }
    else
    {
        if(ui->cbbMode_2->currentText() == "品规")
        {
            sq += " and item_name = '" + ui->leName_2->text() + "'";
            sq += " and specs = '" + ui->leSpecs_2->text() + "'";
        }
        else if(ui->cbbMode_2->currentText() == "厂家")
        {
            sq += " and item_code = '" + item_code + "'";

        }
        else if(ui->cbbMode_2->currentText() == "批号")
        {
            sq += " and item_code = '" + item_code + "'";
            sq += " and batch_no = '" + ui->leBatch_2->text() + "'";
        }
        else if(ui->cbbMode_2->currentText() == "批次")
        {
            sq += " and item_code = '" + item_code + "'";
            sq += " and stock_code = '" + stock_code + "'";
        }
        else
        {
            QMessageBox::information(this,"注意","未指定查询条件！");
            return;
        }
        sq += dateRangeIn ;
    }

    sq += " union select "
          " TO_CHAR (outp.out_date, 'yyyy-mm-dd') 日期,"
          " com_priv_class3.class3_name 入出类型,"
          " outp.out_num / outp.pack_qty 变更数量, "
          " (outp.priv_store_num - outp.out_num ) / outp.pack_qty  结存数量, "
          " outp.pack_unit 单位, outp.out_price 价格,"
          " outp.out_price * outp.out_num / outp.pack_qty 金额, "
          " outp.batch_no 批号,"
          " TO_CHAR (outp.valid_date, 'yyyy-mm-dd') 效期,"
          " f_c.dept_name 供货商,(CASE WHEN outp.out_state = '2' THEN '核准' ELSE '待确认' END ) 状态, "
          " %2 "
          " outp.out_date ord_date , outp.item_name , outp.specs "
          " FROM mat_com_output outp "
          //" LEFT JOIN mat_COM_COMPANY f_c ON "
          //"       f_c.company_CODE = outp.company_CODE "
            " LEFT JOIN com_department f_c ON "
            "       f_c.dept_code = outp.target_dept "
          " LEFT JOIN com_priv_class3 ON "
          "       com_priv_class3.class3_code = out_class3 "
          "       AND com_priv_class3.class2_code = '0520' "
          " %3 "
          " where outp.storage_code = '" + current_dept_code + "' ";

    if(!ui->ckbOut_2->isChecked())
    {
        sq += " and 1> 2 ";  //不查看出库记录, 设置出库常非条件
        //tmp_sq_fld_in = "";  //不查看出库记录,入库相关字段不需要填充
    }
    else
    {
        if(ui->cbbMode_2->currentText() == "品规")
        {
            sq += " and outp.item_name = '" + ui->leName_2->text() + "'";
            sq += " and outp.specs = '" + ui->leSpecs_2->text() + "'";
        }
        else if(ui->cbbMode_2->currentText() == "厂家")
        {
            sq += " and outp.item_code = '" + item_code + "'";

        }
        else if(ui->cbbMode_2->currentText() == "批号")
        {
            sq += " and outp.item_code = '" + item_code + "'";
            sq += " and outp.batch_no = '" + ui->leBatch_2->text() + "'";
        }
        else if(ui->cbbMode_2->currentText() == "批次")
        {
            sq += " and item_code = '" + item_code + "'";
            sq += " and stock_code = '" + stock_code + "'";
        }
        else
        {
            QMessageBox::information(this,"注意","未指定查询条件！");
            return;
        }

        sq += dateRangeOut ;
    }

    sq += "  order by ord_date";

    sq = sq.arg(tmp_sq_fld_in).arg(tmp_sq_fld_out).arg(tmp_sq_tab_out);

    qDebug()<<"提取入库出库明细："<<sq;
    mdList2->setQuery(sq, pub::db_o);

    ui->tvList_2->setModel(mdList2);
    int width = ui->tvList_2->horizontalHeader()->width();
    if(ui->ckbOut_2->isChecked() && store_type == "P")
    {
        //药房，包含出库数据，增加患者姓名等显示列
        pub::setColumnWidth(ui->tvList_2, "0.08^0.08^0.08^0.08^0.08^0.08^0.08^0.08^0.08^0.08^0.06^0.08^0^0.08^0.06", width);
    }
    else
    {
        pub::setColumnWidth(ui->tvList_2, "0.08^0.08^0.08^0.08^0.08^0.08^0.08^0.08^0.08^0.15^0.06", width);
    }
}

bool Form_wzkccx::checkStatus(int mode)
{

    QDate dt1, dt2;
    dt1 = ui->deBegin->date();
    dt2 = ui->deEnd->date();
    if(dt1 > dt2)
    {
        QMessageBox::information(this,"注意","指定的时间范围无效！");
        return false;
    }

    if(dt2 > dt1.addDays(365))
    {
        QMessageBox::information(this,"注意","查询时间范围不允许超过 1 年！");
        return false;
    }

    dt_begin = dt1.toString("yyyy-MM-dd");
    dt_end = dt2.toString("yyyy-MM-dd");

    dateRangeIn = " and trunc(in_date) >= to_date('" + dt_begin + "','yyyy-mm-dd') ";
    dateRangeIn += " and trunc(in_date) <= to_date('" + dt_end + "','yyyy-mm-dd') ";
    dateRangeOut = " and trunc(out_date) >= to_date('" + dt_begin + "','yyyy-mm-dd') ";
    dateRangeOut += " and trunc(out_date) <= to_date('" + dt_end + "','yyyy-mm-dd') ";

    current_dept_code = pub::getStr(store_depts, "^", pub::searchStr(store_depts, "^", ui->cbbStoreDept->currentText()) + 1);

    if(mode == 2)   //出入明细查询
    {
        if(!ui->ckbOut_2->isChecked() && !ui->ckbIn_2->isChecked())
        {
            QMessageBox::information(this, "注意", "入库查询或出库查询至少选定一项！");
            return false;
        }
        if(ui->cbbStoreDept->currentText() == "全部")
        {
            QMessageBox::information(this, "注意", "出入查询必须指定具体库房！");
            return false;
        }

        if(ui->leName_2->text().trimmed().isEmpty())
        {
            QMessageBox::information(this, "注意", "请指定具体品种！");
            return false;
        }

    }

    if(mode == 3)   //出入汇总查询
    {
        if(ui->cbbStoreDept->currentText() == "全部")
        {
            QMessageBox::information(this, "注意", "此项查询必须指定具体库房！");
            return false;
        }

        //        if(!ui->ckbOut_3->isChecked() && !ui->ckbIn_3->isChecked())
        //        {
        //            QMessageBox::information(this, "注意", "入库查询或出库查询至少选定一项！");
        //            return false;
        //        }

        //        if(ui->ckbIn_3->isChecked() && ui->ckbOut_3->isChecked())
        //        {
        //            QMessageBox::information(this, "注意", "不可以同时选择入库查询或出库查询！");
        //            return false;
        //        }

    }

    return true;
}

void Form_wzkccx::on_pbSearch_2_clicked()
{
    QStringList searchResult;
    searchResult = getSearch(ui->cbbMode_2->currentText(), ui->leKey_2->text().trimmed());

    if(searchResult.size() == 0)
    {
        return;
    }
    else
    {
        ui->leName_2->setText(searchResult[0]);
        ui->leSpecs_2->setText(searchResult[1]);
        ui->leFactory_2->setText(searchResult[2]);
        ui->leBatch_2->setText(searchResult[3]);
        item_code = searchResult[4];
        factory_code = searchResult[5];
        stock_no = searchResult[6];
        stock_code = searchResult[7];
    }
}

void Form_wzkccx::on_leKey_2_returnPressed()
{
    on_pbSearch_2_clicked();
}

void Form_wzkccx::on_tabWidget_currentChanged(int index)
{

}

void Form_wzkccx::on_pbDump_clicked()
{
    if(mdList1->rowCount() < 1)
    {
        QMessageBox::information(this, "注意", "无可导出数据 ！" );
        return ;
    }
    ui->pbDump->setEnabled(false);
    qApp->processEvents();
    pub::export_sql_to_excel(last_query_sql, qro);
    ui->pbDump->setEnabled(true);
}

void Form_wzkccx::on_pbInventory_clicked()
{
    //storage_code,
    QString dept_code = "";
    if(ui->cbbStoreDept->currentText() != "全部")
    {
        dept_code = pub::getStr(store_depts, "^", pub::searchStr(store_depts, "^", ui->cbbStoreDept->currentText()) + 1);
    }
    else
    {
        QMessageBox::information(this, "注意", "生成盘点表需要指定具体库房！" );
        return ;
    }
    QString sq;

    // 按厂家划分

    sq = "select (SELECT dept_name FROM COM_DEPARTMENT"
         "        WHERE DEPT_CODE = STO.storage_code AND ROWNUM = 1 ) 库房名称, "
         " sto.item_name 物资项目名称, sto.specs 规格, sto.pack_unit 包装单位,"
         " SUM (store_num / pack_qty) 账面数量, sto.item_code 项目编码, STO.storage_code"
         " FROM MAT_COM_STOCKDETAIL sto"
         " WHERE sto.store_num > 0 AND storage_code = '%1'"
         " group by STO.storage_code, sto.item_name, "
         " sto.specs, sto.pack_unit,  sto.item_code "
         " order by sto.item_name, sto.specs";

    sq = sq.arg(dept_code);

    qDebug()<<"提取盘点表："<<sq;
    mdList3->setQuery(sq, pub::db_o);

    if(mdList3->rowCount() < 1)
    {
        QMessageBox::information(this, "注意", "指定库房无数据！" );
        return;
    }

    ui->tvList->setModel(mdList3);
    int width = ui->tvList->horizontalHeader()->width();
    pub::setColumnWidth(ui->tvList, "0.1^0.25^0.2^0.1^0.2^0", width, 10);

    QMessageBox::StandardButton bt;
    bt = QMessageBox::warning(NULL, "注意", "报表生成完毕，是否打印输出？",QMessageBox::Yes|QMessageBox::No);
    if(bt == QMessageBox::No){
        return;
    }

    QJsonDocument d;
    QJsonArray jsa_val;    //数值

    QJsonObject jot;  // 临时json
    int row = 3;

    int rowCount = 0;

    qro->exec(sq);
    while(qro->next())
    {
        row ++;
        rowCount ++ ;

        jot.insert("val", QString::number(rowCount));
        jot.insert("row", row);
        jot.insert("col", 1);
        jsa_val << jot;

        jot.insert("val", qro->value("物资项目名称").toString());
        jot.insert("row", row);
        jot.insert("col", 2);
        jsa_val << jot;

        jot.insert("val", qro->value("规格").toString());
        jot.insert("row", row);
        jot.insert("col", 3);
        jsa_val << jot;

        jot.insert("val", qro->value("包装单位").toString());
        jot.insert("row", row);
        jot.insert("col", 4);
        jsa_val << jot;

        jot.insert("val", qro->value("账面数量").toString());
        jot.insert("row", row);
        jot.insert("col", 5);
        jsa_val << jot;

        jot.insert("val", qro->value("实际数量").toString());
        jot.insert("row", row);
        jot.insert("col", 6);
        jsa_val << jot;

    }

    jot.insert("val", "库房：" + ui->cbbStoreDept->currentText());
    jot.insert("row", 2);
    jot.insert("col", 1);
    jsa_val << jot;

    jot.insert("val", "品种数量：" + QString::number(rowCount));
    jot.insert("row", 2);
    jot.insert("col", 3);
    jsa_val << jot;

    jot.insert("val", "日期：" + QDate::currentDate().toString("yyyy-MM-dd"));
    jot.insert("row", 2);
    jot.insert("col", 4);
    jsa_val << jot;


    QJsonArray jsa_rng;    //表格区域
    jot = d.object();
    QString rg = QString("A4:F%1").arg(QString::number( rowCount + 3 ));
    jot.insert("range", rg);
    jsa_rng << jot;

    QJsonArray jsa_clr;    //清除区域
    jot = d.object();
    jot.insert("row1",4);
    jot.insert("row2",rowCount);
    jot.insert("col1",1);
    jot.insert("col2",9);
    jsa_clr << jot;


    QJsonObject jo; //打印参数
    jo.insert("excel_model", "/sheets/pandianbiao-wuzi.xls");
    jo.insert("cell_value", jsa_val);
    jo.insert("grid_range", jsa_rng);

    pub::printOutExcel(jo);

}

void Form_wzkccx::on_pbRelate_clicked()
{
    if(!checkStatus(3))
    {
        return;
    }

    if(ui->ckbIn_3->isChecked())
    {
        sq = "SELECT distinct COMPANY.company_name ,INP.COMPANY_CODE"
             " FROM MAT_COM_COMPANY company"
             " LEFT JOIN mat_com_input INP on INP.COMPANY_CODE = COMPANY.COMPANY_CODE "
             " where company.company_type = '1' %1 and inp.storage_code = '%2' ";

        sq = sq.arg(dateRangeIn).arg(current_dept_code);

        qDebug()<<"检索往来关系："<<sq;
        relate_name_code = pub::fillCombo(ui->cbbRelate, sq, 0, qro);
        if(relate_name_code.isEmpty())
        {
            QMessageBox::information(this,"注意","指定时间范围找不到入库数据！");
            return;
        }
        ui->cbbRelate->addItem("全部");

    }
    else //if(ui->ckbOut->isChecked())
    {
        sq = "SELECT distinct dept.dept_name , outp.target_dept"
             " FROM com_department dept"
             " LEFT JOIN mat_com_output outp on outp.target_dept = dept.dept_code "
             " where 1 = 1 %1 and outp.storage_code = '%2' ";

        sq = sq.arg(dateRangeOut).arg(current_dept_code);

        qDebug()<<"检索往来关系："<<sq;
        relate_name_code = pub::fillCombo(ui->cbbRelate, sq, 0, qro);
        if(relate_name_code.isEmpty())
        {
            QMessageBox::information(this,"注意","指定时间范围找不到入库数据！");
            return;
        }
        ui->cbbRelate->addItem("全部");

    }
}

void Form_wzkccx::on_pbFresh_3_clicked()
{
    if(!checkStatus(3))
    {
        return;
    }

    if(ui->cbbRelate->currentText().isEmpty())
    {
        QMessageBox::information(this,"注意","未指定查询的往来关系！");
        return;
    }

    QString relacd = "";
    if(ui->cbbRelate->currentText() != "全部")
    {
        relacd = pub::getStr(relate_name_code, "^", pub::searchStr(relate_name_code, "^", ui->cbbRelate->currentText()) + 1);
        if(ui->ckbIn_3->isChecked())
        {
            //入库
            relacd = " and input.company_code = '" + relacd + "' and input.in_class3 not in('05')"; //不统计核准入库
        }
        else
        {
            //出
            relacd = " and output.target_dept = '" + relacd + "' ";
        }
    }
    else if(ui->ckbIn_3->isChecked())
    {

        relacd = " and input.in_class3 not in('05') ";
    }

    int width = ui->tvList_3->horizontalHeader()->width(); //列表宽度

    if(ui->ckbIn_3->isChecked())
    {
        //入库

        if(ui->ckbItemName->isChecked())
        {
            //按项目名称汇总
            sq = " select item_name 项目名称, item_code 项目编码, max(specs) 规格, sum(in_num / PACK_QTY) 数量,";
            sq += " max(pack_unit) 单位, sum(in_price * in_num / PACK_QTY) 金额 ";
            sq += " FROM MAT_COM_INPUT input ";
            sq += " where storage_code = '" + current_dept_code + "' " + dateRangeIn + relacd ;
            sq += " group by item_code, item_name ";
            sq += " order by item_name ";
        }
        else
        {
            //品种明细
            sq = "SELECT TO_CHAR (in_date, 'yyyy-mm-dd') 日期, priv.class3_name 入库类型, f_c.company_name 供货商,"
                 " item_name 项目名称, item_code 项目编码, specs 规格, in_price 购入价格,"
                 " in_num / PACK_QTY 数量, pack_unit 单位, batch_no 批号, valid_date 效期  "
                 " FROM MAT_COM_INPUT input "
                 " LEFT JOIN MAT_COM_COMPANY f_c ON f_c.company_CODE = input.COMPANY_CODE "
                 " LEFT JOIN com_priv_class3  priv ON priv.class3_code = input.in_class3 AND priv.class2_code = '0510'"
                 " where input.storage_code = '" + current_dept_code + "' " + dateRangeIn  + relacd;
            sq += " order by in_date";

        }

        qDebug()<<"提取入库汇总："<<sq;

        mdList3->setQuery(sq, pub::db_o);

        ui->tvList_3->setModel(mdList3);
        //int width = ui->tvList_3->horizontalHeader()->width();
        //pub::setColumnWidth(ui->tvList_3, "0.08^0.08^0.12^0.12^0.1^0.06^0.06^0.06^0.06^0.08^0.08^0.06^0^0^0^0^0", width, 15);

        if(ui->ckbAmount->isChecked())
        {
            //金额汇总
            sq = "SELECT f_c.company_name 供货商, to_char(round(sum(in_price * in_num / PACK_QTY),2))  金额 "
                 " FROM MAT_COM_INPUT input"
                 " LEFT JOIN MAT_com_company f_c ON f_c.Company_CODE = input.COMPANY_CODE "
                 " where input.storage_code = '" + current_dept_code + "' " + dateRangeIn  + relacd;
            sq += " group by f_c.company_name order by f_c.company_name ";

            qDebug() << "入库金额汇总：" << sq;

            mdList4->setQuery(sq, pub::db_o);

            ui->tvList_4->setModel(mdList4);
            pub::setColumnWidth(ui->tvList_4, "0.2^0.2^0^0^0^0^0", width, 5);
        }
        else
        {
            ui->tvList_4->setModel(NULL);
        }
    }

    if(ui->ckbOut_3->isChecked())
    {
        //出库

        if(ui->ckbItemName->isChecked())
        {
            //按名汇总
            sq = " select item_name 项目名称, item_code 项目编码, max(specs) 规格, sum(out_num / PACK_QTY) 数量,";
            sq += " max(pack_unit) 单位, sum(out_cost) 金额 ";
            sq += " FROM MAT_COM_OUTPUT output";
            sq += " where output.storage_code = '" + current_dept_code + "' " + dateRangeOut + relacd;
            sq += " group by item_code, item_name  ";
            sq += " order by item_name ";
        }
        else
        {
            //明细
            sq = " SELECT TO_CHAR (out_date, 'yyyy-mm-dd') 日期, priv.class3_name 出库类型, C_D.DEPT_NAME 出库对象,"
                 " item_name 项目名称, item_code 项目编码, specs 规格, out_price 购入价格,"
                 " out_num / PACK_QTY 数量, pack_unit 单位, batch_no 批号, to_char(valid_date,'yyyy-mm-dd') 效期"
                 //" PRODUCER_CODE 生产商, COMPANY_CODE, STORAGE_CODE"
                 " FROM MAT_COM_OUTPUT output "
                 " LEFT JOIN COM_DEPARTMENT C_D ON C_D.DEPT_CODE = output.target_dept and ROWNUM = 1 "
                 " LEFT JOIN com_priv_class3 priv ON priv.class3_code = output.out_class3 AND priv.class2_code = '0520'"
                 "  where output.storage_code = '" + current_dept_code + "' " + dateRangeOut + relacd;
            sq += " order by out_date";

        }

        qDebug()<<"提取出库汇总："<<sq;
        mdList3->setQuery(sq, pub::db_o);

        ui->tvList_3->setModel(mdList3);
        //int width = ui->tvList_3->horizontalHeader()->width();
        //pub::setColumnWidth(ui->tvList_3, "0.3^0.2^0.1^0.1^0.1^0.1^0^0^0^0^0^0^0^0^0^0", width, 15);


        if(ui->ckbAmount->isChecked())
        {
            //金额汇总
            sq = " SELECT C_D.DEPT_NAME 出库对象, to_char(ROUND(sum(out_price * out_num / PACK_QTY ),2)） 金额 "
                 " FROM MAT_COM_OUTPUT output "
                 " LEFT JOIN COM_DEPARTMENT C_D ON C_D.DEPT_CODE = output.target_dept and ROWNUM = 1 "
                 "  where output.storage_code = '" + current_dept_code + "' " + dateRangeOut  + relacd;

            sq += " group by C_D.DEPT_NAME order by C_D.DEPT_NAME";

            qDebug()<<"出库金额汇总："<<sq;
            mdList4->setQuery(sq, pub::db_o);

            ui->tvList_4->setModel(mdList4);
            pub::setColumnWidth(ui->tvList_4, "0.2^0.2^0.2^0^0^0^0", width, 5);
        }
        else
        {
            ui->tvList_4->setModel(NULL);
        }
    }

    if(ui->ckbItemName->isChecked())
    {
        pub::setColumnWidth(ui->tvList_3, "0.3^0.2^0.1^0.1^0.1^0.1^0^0^0^0^0^0^0^0^0^0", width, 15);
    }
    else
    {
        pub::setColumnWidth(ui->tvList_3, "0.08^0.08^0.12^0.12^0.1^0.06^0.06^0.06^0.06^0.08^0.08^0.06^0^0^0^0^0", width, 15);
    }
}
